<template>
  <layout>
    <template slot="title">
      <div class="title-container">
        <span style="margin-right: 10px"
          ><b>种粮户信息列表</b>（共{{ total }}户）</span
        >
        <a-button
          type="default"
          icon="plus"
          style="margin-right: 10px; margin-left: 20px"
          :disabled="currentAreaId.length !== 14"
          @click="handlerTableAdd(1)"
          >添加农户</a-button
        >
        <a-button
          type="default"
          icon="plus"
          style="margin-right: 10px; margin-left: 20px"
          @click="handlerTableAdd(2)"
          >添加大户</a-button
        >

        <section class="field-select">
          <label for="">显示表头：</label>
          <a-radio-group v-model="renderFields">
            <a-radio :value="1" icon="bars"> 仅显示种粮户基础信息 </a-radio>
            <a-radio :value="2"> 仅显示种粮户耕地信息 </a-radio>
            <a-radio :value="0" icon="bars"> 显示全部字段 </a-radio>
          </a-radio-group>
        </section>
      </div>
    </template>

    <!-- 顶部操作 -->
    <section slot="search">
      <custom-form
        ref="search-form"
        class="search-form"
        :class="{ 'one-line': isOpen }"
        v-model="tableSearch"
        layout="inline"
        mode="search"
        :FormList="searchColumns"
      >
      </custom-form>

      <section style="margin-top: 4px">
        <a-button
          class="action-button"
          type="default"
          :icon="isOpen ? 'down' : 'up'"
          @click="isOpen = !isOpen"
          >{{ isOpen ? '展开' : '收缩' }}搜索条件字段</a-button
        >
        <a-button class="action-button" type="primary" icon="search" @click="search()"
          >搜索</a-button
        >

        <a-button-group>
          <a-button type="default" @click="handlerTableExportExecl()"
            >按搜索条件导出电子表（模板）</a-button
          >

          <a-button type="default" @click="handlerTableExportExecl(true)"
            >定制导出数据</a-button
          >

          <a-button
            icon="cloud-upload"
            @click="$refs.MemberImport.handlerUploadExecl()"
            >导入电子表更新数据</a-button
          >
        </a-button-group>

        <section class="opreate">
          <!-- <a-popconfirm
            :title="batchIsUsed ? `是否全部取消当前行政区农户的补贴标记？` : '是否全部标记将当前行政区农户为“参与补贴”？'"
            ok-text="确认"
            cancel-text="取消"
            @confirm="batchIsUsed = !batchIsUsed"
          >
            <a-button :loading="(batchIsUsedLoading || tableLoading)">
              <span>批量修改当前行政区下补贴状态</span>
            </a-button>
          </a-popconfirm> -->
          <a-button :loading="tableLoading" @click="handlerBatchChangeStatus">
            <span>批量修改当前行政区下补贴状态</span>
          </a-button>
        </section>

        <a-button @click="handlerBatchModifyMembers"
          >批量修改农户补贴数据</a-button
        >
          <a-button
            type="default"
            :auth="{
              keys: [!(currentAreaId.length < 12)],
              relate: 'and'
            }"
            showDefaultLabel
            @click="handlerPublic()"
          >起草农户公示</a-button>
          <a-button
            type="default"
            :auth="{
              keys: [!(currentAreaId.length < 6)],
              relate: 'and'
            }"
            showDefaultLabel
            @click="handlerPublic(true)"
          >起草大户公示</a-button>

          <a-button
            type="default"
            auth="member.export-fund-release"
            @click="handlerExportExecl(true)"
            >导出资金分户明细表</a-button
          >
      </section>
    </section>

    <!-- 产品列表 -->
    <a-table
      :dataSource="tableData"
      :columns="tableColumns"
      :rowKey="(record) => record.member_id"
      :row-selection="rowSelection"
      :pagination="false"
      :loading="tableLoading"
      @change="handleTableChange"
      class="table-total"
      :scroll="{
        x: '100%',
        y: tableClientHeight,
      }"
      :customRow="customTableRow"
      bordered
    >
      <template slot="member_addr" slot-scope="row">
        <a-tooltip>
          <template slot="title">
            {{ row.member_addr }}
          </template>
          <a-button type="link">{{
            row.member_addr && row.member_addr.length > 6
              ? '...' + row.member_addr.slice(row.member_addr.length - 6)
              : row.member_addr
          }}</a-button>
        </a-tooltip>
      </template>
      <template slot="member_sex" slot-scope="row">
        {{ getLabel(row.member_sex, [], 'member_sex') }}
      </template>
      <template slot="role" slot-scope="row">
        {{ getLabel(row.role, [], 'role') }}
      </template>

      <template slot="member_addr" slot-scope="row">
        <a-tooltip>
          <template slot="title">
            {{ row.member_addr }}
          </template>
          <a-button type="link">{{
            row.member_addr && row.member_addr.length > 6
              ? '...' + row.member_addr.slice(row.member_addr.length - 6)
              : row.member_addr
          }}</a-button>
        </a-tooltip>
        <!-- {{row.member_addr}} -->
      </template>

      <template slot="bt_size" slot-scope="row">
        {{ ((+row.pay_unit === 2 ? +row.field : +row.plant) || 0).toFixed(3) }}
      </template>

      <template slot="plant" slot-scope="row">
        {{ row.plant || 0 }}
      </template>

      <template slot="pay_price_title"> 补贴标准(元/亩) </template>

      <template slot="pay_unit_title"> 补贴面积<br />计算依据 </template>

      <template slot="bt_size_title"> 补贴面积（亩） </template>

      <template slot="pay_price_total_title"> 补贴总金额（元） </template>
      <template slot="field1" slot-scope="row, record, index">
        <span v-if="index === 0">
          {{ row.field1 || 0 }}
        </span>
        <a-button
          v-else
          type="link"
          showDefaultLabel
          @click.stop="handlerManageFarmLand(row, 1)"
          >{{ row.field1 || 0 }}</a-button
        >
      </template>
      <template slot="field2" slot-scope="row, record, index">
        <span v-if="index === 0">
          {{ row.field2 || 0 }}
        </span>
        <a-button
          v-else
          type="link"
          showDefaultLabel
          @click.stop="handlerManageFarmLand(row, 2)"
          >{{ row.field2 || 0 }}</a-button
        >
      </template>
      <template slot="field3" slot-scope="row, record, index">
        <span v-if="index === 0">
          {{ row.field3 || 0 }}
        </span>
        <a-button
          v-else
          type="link"
          showDefaultLabel
          @click.stop="handlerManageFarmLand(row, 3)"
          >{{ row.field3 || 0 }}</a-button
        >
      </template>
      <template slot="plant" slot-scope="row, record, index">
        <span v-if="index === 0">
          {{ (+row.plant_size || 0).toFixed(3) }}
        </span>
        <a-button
          v-else
          type="link"
          showDefaultLabel
          @click.stop="handlePlantEdit(row, 'grain')"
          >{{ (+row.plant_size || 0).toFixed(3) }}</a-button
        >
      </template>

      <!-- 按钮区 -->
      <template slot="action" slot-scope="row, record, index">
        <template v-if="index !== 0">
          <a-button
            class="action-button"
            type="link"
            size="small"
            auth="crop-member.edit"
            @click.stop="handleTableEdit(row)"
            >编辑</a-button
          >
          <a-popconfirm
            title="您确认要删除该条数据?"
            ok-text="确认"
            cancel-text="取消"
            @confirm="tableDel(row)"
          >
            <a-button
              class="action-button"
              type="link"
              auth="crop-member.delete"
              size="small"
              @click.stop
              >删除</a-button
            >
          </a-popconfirm>
          <!-- <a-button
            class="action-button"
            type="link"
            size="small"
            auth="crop-member.plant"
            @click.stop="handlePlantEdit(row, 'grain')"
            >种粮信息</a-button
          > -->
        </template>
      </template>
    </a-table>

    <!-- 产品列表分页器 -->
    <a-pagination
      slot="paging"
      :pageSizeOptions="pageSizes"
      :total="total"
      :show-total="showTotal"
      showSizeChanger
      :pageSize="pageSize"
      v-model="currentPage"
      @showSizeChange="changePageSize"
      @change="changePage"
    >
    </a-pagination>

    <!-- 其他  -->
    <section slot="other">
      <!-- <a-checkbox></a-checkbox>
      <a-button-group>
        <a-button>全选当页</a-button>
        <a-button>全选取消</a-button>
        <a-button>反选当页</a-button>
      </a-button-group> -->
    </section>

    <!-- 编辑产品数据 -->
    <a-modal
      :visible="visible"
      :title="visibleTitle"
      centered
      @cancel="visible = false"
      @ok="handleSubmit"
    >
      <custom-form
        ref="custom-form"
        class="custom-form"
        v-model="currentRow"
        :FormList="formColumns"
        :mode="customMode"
        v-bind="formItemLayout"
        layout="horizontal"
      ></custom-form>
    </a-modal>

    <!-- 管理耕地信息 -->
    <a-modal
      :title="currentRow.member_nam + '-当前确权耕地汇总表'"
      placement="right"
      width="80%"
      :visible="drawerVisible"
      :footer="null"
      :maskClosable="false"
      :bodyStyle="{ maxHeight: '80vh', minHeight: '60vh' }"
      @cancel="handlerFarmLandCancel"
    >
      <Farmland
        :currentField="currentRow"
        :currentFieldType="currentFieldType"
      />
    </a-modal>

    <MemberImport ref="MemberImport" :currentAreaId="currentAreaId" />
  </layout>
</template>

<script lang="ts">
import { Mixins, Component, Watch, Vue, Prop } from 'vue-property-decorator'
import EventsMixin from '@/mixin/events'
import { TableMixin, AuthMixin, AppMixin } from '@/mixin'

import { TableLayout } from '@/layouts'
import CustomForm from '@/components/src/Form'
import { famerServices, IGrain, IMember } from '@/common/services/famer'
import { RosterMixins } from './mixin'
import { BatchChangeUsedStatusMixin } from '../farmers/BatchChangeUsedStatusMixin'
import Farmland from '../grain/Farmland.vue'
import Family from '../list/Family.vue'
import { cropMemberServices } from '@/common/services/crop-member'
import { publicServices } from '@/common/services/public'
import { userModule } from '@/store/modules/user'
import MemberImport from './MemberImport.vue'
import { PublishMixin } from '../farmers/PublishMixin'
import BatchModifyMembers from './BatchModifyMembers.vue'
import { message } from 'ant-design-vue'

@Component({
  components: {
    Layout: TableLayout,
    CustomForm,
    Farmland,
    Family,
    MemberImport,
    BatchModifyMembers,
  },
})
export default class AdminList extends Mixins(
  EventsMixin,
  TableMixin,
  AuthMixin,
  AppMixin,
  PublishMixin,
  RosterMixins,
  BatchChangeUsedStatusMixin
) {
  @Prop({
    type: String,
  })
  public currentAreaName!: string

  get currentUserArea() {
    return userModule.currentUserArea
  }

  public commonParams = {
    s_a_id: '',
  }

  public isOpen = true

  // 产品列表搜索条件
  public tableSearch = {
    // 户主
    role: '',
    is_pub: '',
    is_used: '',
    switch: '2',
  }

  // 筛选条件
  public currentFilter = {
    member_filter: [],
  }

  public formItemLayout = {
    labelCol: { span: 8 },
    wrapperCol: { span: 16 },
  }

  public requireExportFields = ['member_id', 'member_nam', 's_a_id']

  public pageSize = 15

  // 自定义mode
  public customMode = 'add'
  public hasTotalRow = true

  public customRow = (record: IMember) => {
    // 判断是否有异常信息
    return {
      class: {
        'has-error': record.error_msg,
      },
      on: {
        click: () => {},
      },
    }
  }

  // 已选择补贴用户
  public isUsed = 0
  // 批量设置补贴用户状态
  // public batchIsUsed = false;

  // get batchIsUsed() {
  //   return Boolean(+this.isUsed) && (+this.isUsed === +this.total)
  // }
  public batchIsUsed = false

  public batchIsUsedLoading = false
  // public selectedTitle = this.$createElement('span', '是否补贴')

  public customRowSelectionOptions = {
    getCheckboxProps: (record: any) => {
      return {
        props: {
          disabled: !record.member_id, // Column configuration not to be checked
          name: record.name,
        },
      }
    },
  }

  // 当前列表渲染内容
  public renderFields: number = 0 // 0-全部 1-农户 2-耕地

  // 公共字段
  get commonColumns() {
    return [
      {
        title: '补贴状态',
        dataIndex: 'is_used',
        key: 'is_used',
        width: 100,
        fixed: 'left',
        form: {
          type: 'a-radio-group',
          placeholder: '请选择补贴状态',
          isShowList: false,
          renderMode: ['search'],
          isShowFrom: false,
          isShowQuery: true,
          isExport: true,
          dict: [
            {
              label: '已加入',
              value: '1',
            },
            {
              label: '未加入',
              value: '2',
            },
          ],
        },
      },

      {
        title: '是否加入公示',
        dataIndex: 'is_pub',
        key: 'is_pub',
        width: 140,
        form: {
          type: 'a-radio-group',
          placeholder: '请选择补贴状态',
          isShowList: false,
          isShowFrom: false,
          isShowQuery: true,
          dict: [
            {
              label: '已加入',
              value: '1',
            },
            {
              label: '未加入',
              value: '2',
            },
          ],
        },
      },
      {
        title: '公示编号',
        dataIndex: 'pub_id',
        key: 'pub_id',
        width: 140,
        form: {
          type: 'a-input',
          placeholder: '请输入公示编号',
          isShowList: [0, 1].includes(this.renderFields),
          isShowFrom: false,
          isShowQuery: [0, 1].includes(this.renderFields),
        },
      },
      {
        title: '农户/大户编号',
        dataIndex: 'member_id',
        key: 'member_id',
        width: 160,
        customRender: (value: string, row: IMember, index: number) => {
          if (index === 0) {
            return {
              children: value,
              attrs: {
                colSpan: 2,
              },
            }
          }
          return {
            children: value,
          }
        },
        form: {
          type: 'a-input',
          placeholder: '输入农户/大户编号',
          disabled: ['add', 'edit'],
          isShowFrom: false,
          renderMode: ['search'],
          isShowQuery: true,
        },
      },

      // 表单专用
      {
        title: '农户/大户编号',
        key: 'member_id',
        width: 160,
        form: {
          type: 'a-input',
          placeholder: '--自动生成--',
          disabled: ['add', 'edit'],
          renderMode: ['add', 'edit'],
          isShowQuery: false,
          isShowFrom: true,
          isShowList: false,
        },
      },
      {
        title: '农户/大户名称',
        dataIndex: 'member_nam',
        key: 'member_nam',
        customRender: (value: string, row: IMember, index: number) => {
          if (index === 0) {
            return {
              children: value,
              attrs: {
                colSpan: 0,
              },
            }
          }
          return {
            children: value,
          }
        },
        width: 130,
        form: {
          type: 'a-input',
          placeholder: '输入姓名',
          // disabled: ['edit'],
          isShowQuery: true,
          renderMode: ['add', 'edit'],
          // validate: '*'
        },
      },
      {
        title: '类型',
        // dataIndex: 'role',
        key: 'role',
        width: 80,
        scopedSlots: { customRender: 'role' },
        form: {
          type: 'a-radio-group',
          placeholder: '输入姓名',
          isShowQuery: true,
          // disabled: ['edit'],
          disabled: ['edit', 'add'],
          renderMode: ['add', 'edit'],
          dict: [
            {
              label: '农户',
              value: '1',
            },
            {
              label: '大户',
              value: '2',
            },
          ],
          // validate: '*'
        },
      },
      {
        title: '户主身份证/大户执照号',
        dataIndex: 'member_law_id',
        key: 'member_law_id',
        width: 170,
        form: {
          type: 'a-input',
          placeholder: '输入身份证号/营业执照',
          isShowQuery: true,
          renderMode: ['add', 'edit'],
          // validate: '*'
        },
      },
    ]
  }

  // 农户基础信息字段
  public farmerColumns: ITable.IColumn[] = [
    // {
    //   title: '户口本编号',
    //   dataIndex: 'family_book_id',
    //   key: 'family_book_id',
    //   width: 100,
    //   form: {
    //     type: 'a-input',
    //     placeholder: '输入户口本编号',
    //     renderMode: ['add', 'edit'],
    //   }
    // },
    {
      title: '所在地',
      // dataIndex: 'member_addr',
      key: 'member_addr',
      align: 'right',
      width: 120,
      scopedSlots: { customRender: 'member_addr' },
      form: {
        type: 'a-textarea',
        placeholder: '输入家庭住址',
        renderMode: ['add', 'edit'],
      },
    },

    {
      title: '行政编码',
      key: 's_a_id',
      width: 200,
      scopedSlots: { customRender: 's_a_id' },
      form: {
        type: 'a-tree-select',
        placeholder: '请选择所属行政地区到（社/组）一级',
        treeData: [this.defaultCurrentArea],
        tips: '请选择所属行政地区到（社/组）一级',
        renderMode: ['edit'],
        treeNodeFilterProp: 'title',
        loadData: this.onLoadData,
        dropdownStyle: {
          'overflow-y': 'scroll',
          maxHeight: '600px',
        },
        customDisabled: (row) => {
          console.log(row?.init_s_a_id?.length === 14)
          return row?.init_s_a_id?.length === 14
        },
        validate: '*',
        isShowList: false,
        replaceFields: {
          title: 's_a_nam',
          key: 's_a_id',
          value: 's_a_id',
          children: 'children',
        },
        isExport: true,
      },
    },
    {
      title: '手机号',
      dataIndex: 'member_tel',
      key: 'member_tel',
      width: 110,
      form: {
        type: 'a-input',
        placeholder: '输入手机号',
        isShowQuery: true,
        renderMode: ['add', 'edit'],
        // validate: '*'
      },
    },
    {
      title: '银行卡号',
      dataIndex: 'member_bank_num',
      key: 'member_bank_num',
      width: 180,
      form: {
        type: 'a-input',
        placeholder: '输入银行卡号',
        renderMode: ['add', 'edit'],
        isShowQuery: true,
      },
    },
    {
      title: '开户银行',
      key: 'member_bank_code',
      dataIndex: 'member_bank_code',
      width: 150,
      // scopedSlots: { customRender: 'member_bank_code' },
      form: {
        type: 'a-auto-complete',
        placeholder: '选择/输入 开户银行名称',
        showSearch: true,
        renderMode: ['add', 'edit'],
        dataSource: [],
      },
    },
  ]

  // 耕地信息字段
  public fieldColumns: ITable.IColumn[] = [
    // {
    //   title: '确权面积(亩)',
    //   width: 150,
    //   align: 'right',
    //   sorter: true,
    //   sortDirections: ['ascend', 'descend'],
    //   dataIndex: 'field_size',
    //   key: 'field_size',
    //   form: {
    //     type: 'a-input',
    //     placeholder: '请输入确权面积（亩）',
    //     renderMode: ['search', 'edit', 'add'],
    //     isShowQuery: true,
    //     isShowFrom: true,
    //     querySection: true,
    //   },
    // },
    {
      title: '粮食种植面积(亩)',
      align: 'right',
      sorter: true,
      sortDirections: ['ascend', 'descend'],
      scopedSlots: { customRender: 'plant' },
      width: 160,
      key: 'plant_size',
      form: {
        type: 'a-input',
        placeholder: '请输入粮食种植面积（亩）',
        renderMode: ['search', 'edit', 'add'],
        isShowQuery: true,
        isShowFrom: true,
        querySection: true,
      },
    },
    {
      title: '补贴面积（亩）',
      // titleAlias: '补贴面积（亩）',
      slots: { title: 'bt_size_title' },
      // scopedSlots: { customRender: 'bt_size' },
      key: 'bt_size',
      align: 'right',
      dataIndex: 'bt_size',
      sorter: true,
      sortDirections: ['ascend', 'descend'],
      width: 130,
      form: {
        type: 'a-input',
        placeholder: '请输入补贴面积（亩）',
        renderMode: ['edit', 'add'],
        isShowQuery: true,
        querySection: true,
        isShowFrom: true,
      },
    },
    {
      // title: '补贴标准(元/亩)',
      titleAlias: '补贴标准(元/亩)',
      slots: { title: 'pay_price_title' },
      dataIndex: 'pay_price',
      key: 'pay_price',
      align: 'right',
      width: 120,
    },
    {
      // title: '补贴总金额（元）',
      titleAlias: '补贴总金额（元）',
      slots: { title: 'pay_price_total_title' },
      dataIndex: 'bt_price_total',
      key: 'bt_price_total',
      align: 'right',
      // sorter: true,
      // sortDirections: ['ascend', 'descend'],
      width: 140,
    },
  ]

  // 额外的导出字段
  public exportColumns: ITable.IColumn[] = [
    // {
    //   title: '行政编码',
    //   dataIndex: 's_a_id',
    //   key: 's_a_id',
    //   width: 100,
    //   form: {
    //     isShowList: false,
    //     isShowFrom: false,
    //     isShowQuery: false,
    //     isExport: true
    //   }
    // },
    // {
    //   title: '行政地区',
    //   dataIndex: 's_a_nam_all',
    //   key: 's_a_nam_all',
    //   width: 100,
    //   form: {
    //     isShowList: false,
    //     isShowFrom: false,
    //     isShowQuery: false,
    //     isExport: true
    //   }
    // },
  ]

  // 种植粮食信息
  public grainsColumns: ITable.IColumn[] = []

  get formatColumns() {
    return [
      ...this.commonColumns,
      ...this.exportColumns,
      ...([0, 1].includes(this.renderFields) ? this.farmerColumns : []),
      ...([0, 2].includes(this.renderFields) ? this.fieldColumns : []),
      {
        title: '备注',
        dataIndex: 'readme',
        key: 'readme',
        width: 300,
        form: {
          type: 'a-textarea',
          placeholder: '输入备注',
          renderMode: ['add', 'edit'],
        },
      },
      {
        title: '选择查重/查错条件',
        dataIndex: 'member_filter',
        key: 'member_filter',
        width: 260,
        form: {
          type: 'a-checkbox-group',
          placeholder: '请选择查重/查错条件',
          dict: [
            {
              label: '姓名为空',
              value: 'member_nam_empty',
            },
            {
              label: '法定证件号为空',
              value: 'member_law_id_empty',
            },
            {
              label: '联系电话为空',
              value: 'member_tel_empty',
            },
            {
              label: '法定证件号查重',
              value: 'member_law_id_repeat',
            },
            {
              label: '银行卡号查重',
              value: 'member_bank_num_repeat',
            },
            {
              label: '姓名查重',
              value: 'member_nam_repeat',
            },
          ],
          mode: 'multiple',
          renderMode: ['filter'],
          isShowAll: false,
          isShowFrom: false,
          isShowList: false,
          isShowQuery: true,
        },
      },

      // {
      //   title: '农户信息异常原因',
      //   key: 'error_msg',
      //   dataIndex: 'error_msg',
      //   width: 210,
      // },

      // 筛选专用
      {
        title: '操作',
        key: 'action',
        width: 120,
        fixed: 'right',
        scopedSlots: { customRender: 'action' },
      },
    ]
  }

  // 产品列表表格信息
  // @ts-ignore
  public columns: ITable.IColumn[] = this.formatColumns

  public tableApi = {
    list: cropMemberServices.getList,
    add: cropMemberServices.updateCropMember,
    edit: cropMemberServices.updateCropMember,
    del: cropMemberServices.deleteCropMember,
    exportExecl: cropMemberServices.exportCropMemberList,
    // imageUpload: 'uploadStoreImage',
    // imageRemove: 'delStoreImage'
  }

  @Watch('currentAreaId', { immediate: true })
  public handlerCurrentAreaIdChange() {
    this.commonParams.s_a_id = this.currentAreaId
    this.isInitSelected = false
    this.getData()
  }

  @Watch('renderFields')
  public handlerChangeRenderFields() {
    // @ts-ignore
    this.columns = this.formatColumns
  }

  public mounted() {
    // @ts-ignore
    // @todo 复选框权限控制
    // this.rowSelection.getCheckboxProps = (record) => {
    //   return {
    //     disabled: true
    //   }
    // }
    this.handlerAddGrainColumn()
  }

  public handlerAddGrainColumn() {
    const grains = [
      '水稻',
      '玉米',
      '小麦',
      '红苕',
      '马铃薯',
      '大豆',
      '绿豆',
      '豌葫豆',
      '高粱',
      '荞麦',
      '肾豆',
      '红小豆',
      '其他作物',
    ]
    const grainsColumns = grains.map((item, index) => {
      const last: boolean = index === grains.length - 1
      const key: string = `plant${last ? '_else' : index + 1}`
      return {
        title: item,
        dataIndex: key,
        key,
        form: {
          type: 'a-input',
          placeholder: `请输入${item}面积`,
          renderMode: ['grain'],
          isShowList: false,
        },
      }
    })
    // @ts-ignore
    this.columns = this.columns.concat(grainsColumns)
  }

  public handlerTableAdd(role: string) {
    this.tableAdd()
    setTimeout(() => {
      this.currentRow = Object.assign(
        {},
        {
          role: `${role}`,
        }
      )
      this.customMode = 'add'
      this.visibleTitle = '添加补贴对象'
    })
  }

  // 编辑农户基础数据
  public async handleTableEdit(row: any, mode: string = 'edit') {
    this.customMode = mode
    this.tableApi.edit = cropMemberServices.updateCropMember
    this.tableEdit(
      Object.assign({}, row, {
        init_s_a_id: row.s_a_id,
      })
    )
    this.visibleTitle = `编辑${+row.role === 1 ? '农户' : '大户'}基础信息`
  }

  get totalPlant() {
    if (typeof this.currentRow.plant1 === 'undefined') return 0
    let count = 0
    Object.keys(this.currentRow)
      .filter((_) => !_.includes('size') && /^plant(.+)/.test(_))
      .forEach((key) => {
        count += +this.currentRow[key] || 0
      })
    return count.toFixed(3)
  }

  @Watch('totalPlant')
  public handlerChangeCurrent() {
    this.visibleTitle =
      this.currentRow.member_nam +
      ' 粮食种植面积（亩），当前总计' +
      this.totalPlant +
      '亩'
  }

  // 编辑种粮数据
  public async handlePlantEdit(row: IGrain, mode: string) {
    this.customMode = mode
    this.tableApi.edit = cropMemberServices.updateCropMemberPlant
    cropMemberServices
      .getCropMemberPlants({
        member_id: row.member_id,
        s_a_id: row.s_a_id,
      })
      .then((res) => {
        this.tableEdit(
          Object.assign(
            {},
            row,
            res.data || {
              plant1: 0,
              plant2: 0,
              plant3: 0,
              plant4: 0,
              plant5: 0,
              plant6: 0,
              plant7: 0,
              plant8: 0,
              plant9: 0,
              plant10: 0,
              plant11: 0,
              plant12: 0,
            }
          )
        )
        if (mode === 'grain') {
          this.$nextTick(() => {
            this.visibleTitle =
              // @ts-ignore
              row.member_nam +
              ' 粮食种植面积（亩），当前总计' +
              this.totalPlant +
              '亩'
          })
        }
      })
  }

  public drawerVisible = false
  public currentFieldType = 1
  // 管理耕地信息
  public handlerManageFarmLand(row: IGrain, mode: number) {
    this.currentRow = Object.assign({}, row)
    this.currentFieldType = mode
    this.drawerVisible = true
  }

  public handlerFarmLandCancel() {
    this.drawerVisible = false
    this.getData()
  }

  // 默认配置
  get defaultCurrentArea() {
    return {
      s_a_id: this.currentUserArea?.s_a_id,
      s_a_nam: this.currentUserArea?.s_a_nam,
      selectable: this.currentUserArea?.s_a_id?.length === 14,
    }
  }

  @Watch('defaultCurrentArea')
  public handlerChangedefaultCurrentArea() {
    console.log(this.defaultCurrentArea, 'defaultCurrentArea')
  }

  public async onLoadData(treeNode?: any) {
    const res = await publicServices.getAreaLazy({
      s_a_id: treeNode
        ? treeNode.dataRef.s_a_id
        : this.currentUserArea?.s_a_id || '0',
    })
    // 判断是否是叶子节点
    const treeData = res.data.map((item) => {
      if (item.s_a_id.length === 14) {
        // @ts-ignore
        item.isLeaf = true
      } else {
        // @ts-ignore
        item.selectable = false
      }
      return item
    })
    if (!treeNode) {
      this.changeDict('s_a_id', treeData, 'treeData')
    } else {
      treeNode.dataRef.children = treeData
      const currentTreeData = this.columns.find((column) => {
        return 's_a_id' === column.key && column.form
      })
      this.changeDict(
        's_a_id',
        [...(currentTreeData?.form?.treeData || [])],
        'treeData'
      )
    }
  }

  // 批量修改用户信息
  public handlerBatchModifyMembers() {
    this.$dialog(
      BatchModifyMembers,
      {
        currentAreaId: this.currentAreaId,
      },
      {
        title: '批量修改 ' + this.currentAreaName + ' 农户补贴数据',
        width: '500px',
        on: {
          async ok() {
            // @ts-ignore
            const data = await this.$refs._component.handlerSubmit()
            message.success('修改成功')
            return true
          },
        },
      }
    )
  }

  // 重写Mixin的方法
  public handlerUpdateUsedStatus(selectUsedStatus: string) {
    if (!selectUsedStatus) {
      this.$message.error('请选择批量操作的补贴状态！')
      return
    }
    this.batchChangeUsedLoading = true
    return cropMemberServices
      .setCropMemberUsed({
        is_area: this.currentAreaId,
        is_used: selectUsedStatus,
      })
      .then(() => {
        this.getData()
        this.$message.success('补贴状态更新成功')
      })
      .finally(() => {
        this.batchChangeUsedLoading = false
      })
  }
}
</script>

<style scoped lang="less">
@import './MemberList.less';
.action-button {
  margin: 0px 10px 0px 10px;
}
.form-item-class {
  margin-bottom: 0px;
}
.img-box {
  width: 100px;
  height: 100px;
  margin: 10px;
}
.item-blue {
  color: #1989fa;
}

/deep/ .ant-table-thead th {
  // text-align: center!important;
}

/deep/ .ant-card-head-title {
  padding-top: 0px !important;
}

.opreate {
  margin-left: 6px;
  margin-right: 10px;
  display: inline-block;
}
.page-title {
  display: flex;
  align-items: center;
}

/deep/ th[key='selection-column'] {
  position: relative;
  padding-top: 24px !important;
  padding-bottom: 0 !important;
  &::after {
    content: '补贴';
    position: absolute;
    top: 10px;
    left: 50%;
    width: 100%;
    transform: translateX(-50%);
  }
}

.message-tips {
  margin-bottom: 10px;
  display: flex;
  align-items: center;
}

/deep/ .has-error {
  background-color: rgba(255, 173, 50, 0.1);
}
.one-line {
  height: 40px;
  overflow: hidden;
}
/deep/ .search-form {
  .form_item_is_used,
  .form_item_is_pub,
  .form_item_member_filter {
    .ant-form-item-label {
      font-weight: bold;
    }
  }
}

/deep/ .ant-table {
  thead tr {
    background: #fafafa;
  }

  tbody tr {
    background: #fff;
  }
  th[key='member_nam'],
  tr:not(:nth-child(1)) td:nth-of-type(5) {
    position: sticky;
    left: 60px;
    top: 0;
    z-index: 99;
    background: inherit;
  }
}
</style>
